<!--
 * @Description: 地图容器
 * @Author: liushuang
 * @Date: 2022-05-10 09:39:00
 * @LastEditTime: 2022-12-02 18:02:06
-->
<template>
  <div id="mapContainer">
    <!-- 地图加载动画 -->
    <div class="loading" v-if="mapLoading">
      <KMapLoading></KMapLoading>
    </div>
  </div>
</template>

<script setup>
import initMap from '@/utils/map'
import {
  watch,
  onBeforeUnmount,
  defineEmits,
  ref,
  shallowRef
} from 'vue'
import mapUtils from '@/utils/mapUtils' // 地图相关工具函数
import KMapLoading from '@/components/KMapLoading/index.vue'

const mapLoading = ref(true)
const { AMapBase, map } = initMap({ id: 'mapContainer' }) // 初始化地图

// 地图点击事件 父组件响应
const emits = defineEmits(['handleMap', 'getMapObj'])

const MapUtils = shallowRef(null)
/**
 * @desc: 初始化地图渲染对象
 */
const initMapUtils = () => {
  MapUtils.value = mapUtils(AMapBase, map)
}

/**
 * @desc: 地图绑定事件
 */
const bindMapEvents = () => {
  // 地图层级改变 关闭聚合点信息弹窗
  map.value.on('click', (e) => {
    console.log('点击地图', e)
  })
}

// 监听地图被初始化
watch(map, (newMap) => {
  if (newMap) {
    mapLoading.value = false
    initMapUtils()
    bindMapEvents()
    // eslint-disable-next-line no-use-before-define
    emits('getMapObj', { map, AMapBase, MapUtils })
  }
})

onBeforeUnmount(() => {
  MapUtils.value = null
  // 销毁地图，并清空地图容器
  map.value.destroy()
})
</script>
<style scoped>
#mapContainer {
  width: 100%;
  height: 100%;
  min-width: 10px;
  min-height: 10px;
}
.loading {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 99;
}
</style>
